<?php

class PhotoPage extends Page {
    static $has_many = array(
        'PhotoAlbums' => 'PhotoAlbum',
    );

    public function getCMSFields(){
        $f = parent::getCMSFields();
        $AlbumManager = new DataObjectManager(
            $this,
            'PhotoAlbums',
            'PhotoAlbum',
            array(
                'Title' => 'Titel',
                'Date' => 'Datum',
                'Archive' => 'Gearchiveerd'
            ),
            'getCMSFields_forPopup'
        );
        $f->addFieldToTab("Root.Content.FotoAlbums", $AlbumManager);
        return $f;
    }
}

class PhotoPage_Controller extends Page_Controller {

    public function init(){
        parent::init();
        Requirements::themedCSS('Photo');
    }

    public function PhotoAlbums(){
        return DataObject::get('PhotoAlbum', 'PhotoAlbum.PhotoPageID = ' . $this->ID . ' AND PhotoAlbum.Archive = 0');
    }

    /**
     * JSON: retourneert de foto's uit het gekozen album
     * accepteert een request arg: het ID van het album
     */
    public function GetAlbumContent(){
        $AlbumID = Director::urlParam("ID");
        if(!preg_match('/^[0-9]{1,9}$/i', $AlbumID)){
            die('Ongeldig argument.');
        }
        $Album = DataObject::get('PhotoAlbum', 'PhotoAlbum.ID = ' . $AlbumID);
        $RSS = $Album->items[0]->RSSFeed;
        $RSS = 'https://picasaweb.google.com/data/feed/base/user/nsvisser/albumid/5520243479400962721?alt=rss&kind=photo&authkey=Gv1sRgCL652sTa7ciNPA&hl=nl';
        $XMLData = file_get_contents($RSS);
        $XML = simplexml_load_string($XMLData);
        $json = array();
        foreach($XML->channel->item as $entry){
            $i = count($json);
            $json[$i] = array();
            $json[$i]['desciption'] = (string)($entry->title);
            $json[$i]['url'] = (string)($entry->enclosure['url']);
        }
        return json_encode($json);
    }
}